package com.xyzwps.ewa.modules.auth

import com.xyzwps.ewa.common.CookieNames
import com.xyzwps.ewa.common.ServerException
import com.xyzwps.ewa.ext.userId
import com.xyzwps.ewa.modules.auth.session.Sessions
import io.ktor.http.*
import io.ktor.server.routing.*

fun Route.auth(
    build: Route.() -> Unit
): Route {
    val authedRoute = createChild(AuthedRouterSelector())
    authedRoute.build()
    return authedRoute
}

internal class AuthedRouterSelector : RouteSelector() {
    override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {
        val sessionId = context.call.request.cookies[CookieNames.SID] ?: throw unauthenticated()
        val session = Sessions.get(sessionId) ?: throw unauthenticated()
        if (session.isExpired) throw unauthenticated()

        context.call.attributes.userId(session.userId)

        return RouteSelectorEvaluation.Transparent
    }

    private fun unauthenticated() = ServerException("Unauthenticated", HttpStatusCode.Unauthorized)
}